package com.boot.unity.api.Interceptor;

import com.alibaba.fastjson.JSON;
import com.boot.unity.api.common.ResponseResult;
import com.boot.unity.api.common.Result;
import com.boot.unity.api.common.ResultCodeEnum;
import com.boot.unity.api.common.wrapper.CustomRequestWrapper;
//import com.boot.unity.api.modules.cert.entity.Cert;
import com.boot.unity.api.utils.IpUtil;
import com.boot.unity.api.utils.SignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@AllArgsConstructor
public class SignInterceptor extends HandlerInterceptorAdapter {
//    private final RedisTemplate<String, Cert> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CustomRequestWrapper requestWrapper = (CustomRequestWrapper) request;
        boolean pass = true;//SignUtil.validateSign(requestWrapper,redisTemplate);
        if (pass){
            return true;
        }else {
            log.error("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",
                    request.getRequestURI(),
                    IpUtil.getIpAddress(request),
                    JSON.toJSONString(request.getParameterMap()));
            Result result = new Result(ResultCodeEnum.CERT_ERROR);
            ResponseResult.toJsonResult(response, result);
            return false;
        }
//        String uri = request.getRequestURI();
//        AntPathMatcher matcher = new AntPathMatcher();
//        if (matcher.match(Constants.API_URI_PREFIX,uri)){
//            boolean pass = SignUtil.validateSign(request);
//            if (pass){
//                return true;
//            }else {
//                log.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",
//                        request.getRequestURI(),
//                        IpUtil.getIpAddress(request),
//                        JSON.toJSONString(request.getParameterMap()));
//                Result result = new Result(ResultCodeEnum.CERT_ERROR);
//                ResponseResult.toJsonResult(response, result);
//                return false;
//            }
//        }
//        return true;
    }
}
